<template>
  <div class="detailConsultant-page">
    <GhNavBar title="咨询师详情"  />
     <div class="detail-content">
         <div class="img">
            <img :src="detailInfo.avatar" alt="">
             <div class="mark">
               <img src="@/assets/protect.png" alt="">
             </div>
         </div>
         <div class="personalInfo">
            <div class="top-card">
                <div class="top_item">
                    <div class="name">{{detailInfo.name}} <span class="label">{{detailInfo.coun_label}}星心理咨询师</span></div>
                    <div class="price"><span class="yuan">￥</span>100<span>/小时</span></div>
                </div>
               <div class="bottom-item">
                 <span>面询·视频咨询</span>
                 <span class="instruction"> <gh-icon class="icon" name="consult-instruction"></gh-icon>深圳工作室</span>
               </div>
               <div class="card-title"> <gh-icon class="icon" name="consult-experience"></gh-icon>咨询经验</div>
               <div class="experience-items">
                <div class="exp_year">
                    <p>从业时长</p><p class="bottom_time"><span>{{detailInfo.experience}}</span>年</p>
                  </div>
                  <div class="exp_year">
                    <p>咨询经验</p><p class="bottom_time"><span>{{detailInfo.experience*300}}</span>+小时</p>
                  </div>
                  <div class="exp_year">
                    <p>1对1督导</p><p class="bottom_time"><span>{{detailInfo.experience*20}}</span>+小时</p>
                  </div>
               </div>
            </div>
             <div class="bottom-card">
                 <div class="intro-box">
                    <p> <gh-icon class="icon" name="consult-introduction"></gh-icon>个人简介</p>
                    <p class="text-content">{{detailInfo.introduction}}</p>
                 </div>
                 <div class="appointment-box">
                    <p class="booking-time"><gh-icon class="icon" name="consult-time"></gh-icon>可约时间</p>
                    <p class="confirm">咨询时长：120分钟/节</p>
                    <div class="calendar-box">
                        <!-- <van-calendar
                            :poppable="false"
                            :show-confirm="false"
                            :show-title="false"
                            :min-date="minDate" 
                            :max-date="maxDate"
                          >
                        </van-calendar> -->
                       <!-- 预约日期列表 -->
                        <van-swipe
                        :loop="false"
                        :show-indicators="false"
                        :width="60"
                        ref="dateSwipe"
                      >
                        <van-swipe-item v-for="date in tran_dates" :key="date" >
                          <div class="date" @click="selectDate(date)" :class="{ active: selectedDate === date.date }">
                                <p class="month">{{date.month}}月</p>
                                <p class="day">{{date.day}}</p>
                                <p class="week">{{date.week}}</p>
                                <div class="status">
                                    <p>点击</p>
                                    <p>查看</p>
                                </div>
                          </div>
                        </van-swipe-item>
                      </van-swipe>
                      <div class="date-info">
                        <!-- <div class="info" v-if="selectedDate">
                          {{ selectedDate }}
                        </div> -->
                        <!-- 空闲时间展示表 -->
                        <div class="availability-box" v-if="timeSlots.length>0">
                             <div  class="time-slot"  v-for="timeSlot in timeSlots" :key="timeSlot.id" @click="selectTime_Slot(timeSlot)"
                             :class="{ 'selected': timeSlot.id === selectedTimeSlotId, 'booked': timeSlot.is_booked }"> 
                              {{ timeSlot.start_time }} - {{ timeSlot.end_time }}
                              <div class="is_selected" v-if="timeSlot.id===selectedTimeSlotId"><gh-icon class="icon" name="consult-selected"></gh-icon></div>
                              <div class="is_booked" v-else-if="timeSlot.is_booked===null||0">可预约</div>
                              <div class="unbooked" v-else-if="timeSlot.is_booked===1">已预约</div>
                            </div>
                            
                        </div>
                        <div class="nothing-info" v-else>
                            <van-empty  image-size="100" description="暂无可预约时间" />
                        </div>
                      </div>

                    </div>
                    <div class="instructions">
                         <div class="ins_title">预约须知</div>
                         <div class="ins_content">
                            <div class="f_title">
                                <gh-icon class="icon" name="consult-instruction"></gh-icon>   回应时长
                                <p> 我将在收到订单后6小时内回复是否接受咨询，且在12小时内通过私信与来访者协商咨询时间、地点；</p>
                            </div>
                            <div class="f_title">
                                <gh-icon class="icon" name="consult-instruction"></gh-icon>   变更预约说明
                                <p>  若因为不可抗力需要变更/取消已协商好的咨询预约，请提前24小时与我协商更改。</p>
                            </div>
                            <div class="f_title">
                                <gh-icon class="icon" name="consult-instruction"></gh-icon>    爽约/迟到说明
                                <p>  若没有提前24小时告知情况，爽约/迟到30分钟以上，则默认这次咨询已经完成，特殊情况请与我协商处理。</p>
                            </div> 
                         </div>
                    </div>
                 </div>
             </div>
         </div>
     </div>
   <div class="booking_box" v-if="!isConsultant">
    <div class="chat_o"> <gh-icon class="icon" name="consult-kefu"></gh-icon>客服</div>
    <van-button class="booking" native-type="submit" block round @click="submit" >
        立即预约
      </van-button>
   </div>
   <van-action-sheet v-model:show="show" title="请选择支付方式">
         <div class="content">
          <p class="amount">￥120</p>
          <van-cell-group>
            <van-cell title="微信支付" @click="paymentMethod = 0">
              <template #icon><gh-icon name="consult-wechat" /></template>
              <template #extra>
                <van-checkbox :checked="paymentMethod === 0" />
              </template>
            </van-cell>
            <van-cell title="支付宝支付" @click="paymentMethod = 1">
              <template #icon><gh-icon name="consult-alipay" /></template>
              <template #extra>
                <van-checkbox :checked="paymentMethod === 1" />
              </template>
            </van-cell>
          </van-cell-group>
          <div class="btn">
            <van-button @click="pay" type="primary" :loading="isRegistering" :disabled="isRegistering"  round block> 立即支付 </van-button>
          </div>
         </div>
  </van-action-sheet>
  </div>
</template>

<script setup>
import {ref,reactive,onBeforeMount,computed,onMounted,watch} from "vue"
import { Toast, Dialog } from 'vant';
import 'vant/es/toast/style'
import{useRouter,useRoute}from 'vue-router'
const router =useRouter();  
const route =useRoute()
import {getDetailConsultantInfo,getavailableTime,getAvailableToday,getAvailableByTime,appointment} from '@/services/booking'

//存储空闲时间段数据
const timeSlots=ref([])
const show=ref(false)
// 选中的日期
 const selectedDate = ref(null);
 const dates = ref([]);
 const tran_dates=ref([])
 // 初始化日期列表
 const initDates = () => {
      const currentDate = new Date();
      for (let i = 0; i < 7; i++) {
        const date = new Date(currentDate);
        date.setDate(date.getDate() + i);
        dates.value.push(date);
      }
    const formttedDates= dates.value.map(date=>{
        return {date:formData(date),month:String(date.getMonth() + 1).padStart(2, '0'),day:String(date.getDate()).padStart(2, '0'),week:date.toLocaleString('default',{weekday:'short'})}
      })
     tran_dates.value=formttedDates
      selectedDate.value = formData(dates.value[0]);
    };
    
// 格式化日期
const formData = (date) => {
      const year = date.getFullYear();
      const month = (date.getMonth() + 1).toString().padStart(2, '0');
      const day = date.getDate().toString().padStart(2, '0');
      return `${year}-${month}-${day}`;
    };

//定义选中的响应式变量
const selectedTimeSlotId=ref()
const booking_time=ref()

//选择预约时间段
const selectTime_Slot=(timeSlot)=>{
  selectedTimeSlotId.value=timeSlot.id
  console.log(timeSlot)
   booking_time.value=timeSlot

}

 // 选择日期
 const selectDate = async(date) => {
      selectedDate.value = date.date
      const id=route.params.id
      const time=selectedDate.value
      const res=await getAvailableByTime(id,time)
      const timeData=res.data
      //对时间进行格式处理
      const timeDatas= timeData.map(row=>{
     const date=row.start_time.split(' ')[0];
     const timePart_start=row.start_time.split(' ')[1]
     const timePart_end=row.end_time.split(' ')[1]
     // 再次拆分时间部分并获取小时和分钟部分
    var timeParts_start = timePart_start.split(":");
    var timeParts_end = timePart_end.split(":");
    var timePartData_start = timeParts_start[0] + ":" + timeParts_start[1]; // 只获取小时和分钟    
    var timePartData_end = timeParts_end[0] + ":" + timeParts_end[1];
    return{
      id:row.id,
      coun_id:row.coun_id,
      date:date,
      start_time:timePartData_start,
      end_time:timePartData_end,
      is_booked:row.is_booked
    }
   })
    // console.log(timeDatas)
    timeSlots.value=timeDatas
   };

    initDates()
//判断进入页面的是不是咨询师响应式变量
const isConsultant=ref(false)
//咨询师详情信息响应式变量
const detailInfo=ref([])
onBeforeMount(async()=>{
  const role=JSON.parse(localStorage.getItem('gh-user')).user.userData.role
  if(role=='counselor'){
      isConsultant.value=true
  }
    let id =route.params.id
    const res=await getDetailConsultantInfo(id)
    detailInfo.value=res.data
})

onMounted(async()=>{
    let id =route.params.id
    const today =formData(new Date())
   const todayTime=await getAvailableToday(id,today)
    const todayTimeData=todayTime.data
    // console.log(todayTimeData)
   const todayTimeSlot= todayTimeData.map(row=>{
     const date=row.start_time.split(' ')[0];
     const timePart_start=row.start_time.split(' ')[1]
     const timePart_end=row.end_time.split(' ')[1]
     // 再次拆分时间部分并获取小时和分钟部分
    var timeParts_start = timePart_start.split(":");
    var timeParts_end = timePart_end.split(":");
    var timePartData_start = timeParts_start[0] + ":" + timeParts_start[1]; // 只获取小时和分钟    
    var timePartData_end = timeParts_end[0] + ":" + timeParts_end[1];
    return{
      id:row.id,
      coun_id:row.coun_id,
      date:date,
      start_time:timePartData_start,
      end_time:timePartData_end,
      is_booked:row.is_booked
    }
   })
    timeSlots.value=todayTimeSlot
    const allTime=await getavailableTime(id)
    alltime.value=allTime.data
    // console.log(alltime.value)
    // 统计每个日期的预约数据
  const dateCounts = new Map();
    alltime.value.forEach(data => {
    const date = data.start_time.split(' ')[0];
   if (dateCounts.has(date)) {
     dateCounts.set(date, dateCounts.get(date) + 1);
    } else {
     dateCounts.set(date, 1);
    }
    });
    // 根据统计数据生成格式化后的信息
  const formattedData = alltime.value.map(data => {
  const date = data.start_time.split(' ')[0];
  const count = dateCounts.get(date) || 0;

  return {
    id: data.id,
    coun_id: data.coun_id,
    start_time: data.start_time,
    end_time: data.end_time,
    is_booked: data.is_booked,
    status: count > 0 ? `剩余${count}` : '暂无信息'
  };
 });
//  console.log(formattedData);
})
const alltime=ref([])
const status=ref()

//立即预约提交功能
const submit=async()=>{
  if(!booking_time.value){
     Toast('请先选择预约时间！')
     return
  }
  show.value=true
  
}
const paymentMethod=ref()
const isRegistering = ref(false);
//立即支付
const pay=async()=>{
  // console.log(paymentMethod.value)
  if(!paymentMethod.value&&paymentMethod.value!==0){
    Toast('请选择支付方式')
    return
  }
  isRegistering.value=true
  setTimeout(async() => {
  const counselor_id =route.params.id
  const date =new Date(booking_time.value.date)
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始，需要加1
  const day = String(date.getDate()).padStart(2, '0'); // 日期格式化为两位数
  const formattedDate = `${year}-${month}-${day}`;
  const start_time=booking_time.value.start_time
  const end_time=booking_time.value.end_time
  const account=JSON.parse(localStorage.getItem('gh-user')).user.userData.account
  const formData=new FormData()
  formData.append('account',account)
  formData.append('counselor_id',counselor_id)
  formData.append('date',formattedDate)
  formData.append('start_time',start_time)
  formData.append('end_time',end_time)
  formData.append('selectedTimeSlotId',selectedTimeSlotId.value)
  const res=await appointment(formData).then((response)=>{
      return response
    }).catch((error)=>{
     return error
    })
   if(res.status!==201){
   if(res.response.status==402){
        const toastMessage=res.response.data.error
        Toast.fail(toastMessage)
        isRegistering.value=false;
        return
    }
    if(res.response.status==404){
        const toastMessage=res.response.data.error
        Toast.fail(toastMessage)
        isRegistering.value=false;
        return
    }
  }
  console.log(res)
  Toast.success('预约成功')
  router.push('/booking')
    isRegistering.value=false
  }, 1000);

}

</script>

<style lang="scss" scoped>
.detailConsultant-page{
    width: 100%;
    .detail-content{
        width: 100%;
        margin-top: 40px;
        .img{
            position: relative;
            width: 100%;
            height: 180px;
            background-color:#f5f5f5;
            border-radius: 8px;
            img{
                display: block;
                width: 100%;
                height: 100%;
                border-radius: 8px;
            }
            .mark{
              position: absolute;
              bottom: 0;
              left: 0;
              box-sizing: border-box;
              width: 100%;
              height: 40px;
              border-radius: 8px;
                 img{
                    width: 100%;
                    height: 100%;
                    display: block;  
                    border-radius: 8px;
                 }

            }
        }
        .personalInfo{
            position: relative;
            width: 100%;
            /* height: 300px; */
            background-color: #f5f5f5;
            .top-card{
                position: absolute;
                width: 100%;
                border: #f5f5f5 10px solid; 
                height: 280px;
                background-color: #fff;
                padding: 15px 10px ;
                border-radius: 15px;
                .top_item{
                    display: flex;
                    justify-content: space-between;
                    align-items: center;
                    .name{
                         display: flex;
                         flex: 1;
                         font-size: 20px;
                         font-weight: bold;
                         font-family: '黑体';
                         .label{
                            text-align: center;
                            line-height: 20px;
                            font-size: 10px;
                            margin-left: 10px;
                            height: 20px;
                            width: 80px;
                            color:#C16019;
                            background-color: #FFF4DC;
                         }
                  
                   }
                     .price{
                       color: red;
                       font-weight: bold;
                       font-size: 26px;
                       margin-right: 10px;
                       .yuan{
                         vertical-align:text-top;
                         font-size: 12px;
                        }
                       span{
                         font-size: 14px;
                      }
                  }
                }
                .bottom-item{
                    margin-top: 8px;
                    padding: 0 5px 15px;
                    font-size: 12px;
                    border-bottom: 1px solid var(--gh-line);
                    color: #808185;
                    position: relative;
                    .instruction{
                       position: absolute;
                       right: 16px;
                       .icon{
                        display: inline-block;
                        margin-right: 5px;
                        font-size: 12px;
                        text-align: center;
                        line-height: 12px;
                       }
                    }
                }
                .card-title{
                    color: #1F2229;
                    padding: 10px 10px;
                    .icon{
                        font-size: 14px;
                        margin-right: 5px;
                    }
                }
                .experience-items{
                    display: flex;
                    justify-content: space-between;
                    align-items: center;
                    padding:  0 15px;
                    margin-bottom: 10px;
                    .exp_year{
                        p{
                            color: #808185;
                            font-size: 12px;
                        }
                        .bottom_time{
                            color: black;
                            font-size: 12px;
                            font-weight: bold;
                            span{
                                font-size: 18px;
                                font-weight: bold;
                            }
                        }
                    
                    }
                }
               
            }
            .bottom-card{
                position: absolute;
                width: 100%;
                top: 210px;
                border-radius: 15px;
                padding: 15px 10px;
                /* height: 220px; */
                background-color: #fff;
                border: #f5f5f5 10px solid;
                .intro-box{
                    p{
                        font-size: 17px;
                        font-weight: bold;
                        .icon{
                            font-size: 20px;
                            margin-right: 5px;
                            text-align: center;
                            display: inline-block;
                            line-height: 20px;
                        }
                    }
                    .text-content{
                        font-size: 14px;
                        padding: 8px 10px;
                        color: #808185;
                        font-weight: normal;
                        text-indent: 2rem;
                    }
                }
                .appointment-box{
                    margin-top: 10px;
                    padding: 0 10px 28px;
                    /* height: 100px; */
                    .booking-time{
                    font-size: 17px;
                    font-weight: bold;
                      .icon{
                        font-size: 17px;
                        margin-right: 5px;
                      }
                    }
                    .confirm{
                        padding: 10px;
                        font-size: 12px;
                        color: #808185;
                    }
                    .calendar-box{
                        /* height: 300px; */
                        margin-bottom: 20px;
                        .van-swipe{
                            margin-top: 10px;
                            height: 130px;
                            width: 100%;
                            .date{
                                text-align: center;
                                width: 100%;
                                height: 100%;
                                display: flex;
                                flex-direction: column;
                                justify-content: center;
                                align-items: center;
                                .month{
                                    font-size: 12px;
                                    color: #808185;
                                }
                                .day{
                                    font-size: 17px;
                                    font-weight: bold;
                                }
                                .week{
                                    font-size: 10px;
                                }
                                .status{
                                    display: flex;
                                    flex-direction: column;
                                    font-size: 10px;
                                    background-color:#e9eaf1;
                                    margin-top: 10px;
                                    height: 45px;
                                    width: 40px;
                                    border-radius:6px;
                                    align-items: center;
                                    justify-content: center;
                                    text-align: center;
                                }
                            }
                            .date.active{
                                background-color: var(--gh-primary);
                                color: #fff;
                                border-radius: 8px;
                                .status{
                                    color: #000;
                                    background-color: #fff;
                                }
                            }
                        }
                        .date-info{
                            width: 100%;
                            text-align: center;
                            /* height: 200px; */
                            .info{
                                 width: 100%;
                            }
                            .nothing-info{
                                margin-top: 10px;
                                width: 100%;
                                height:200px;
                                background-color: #f5f5f5;
                                .van-empty{
                                    height: 100%;
                                    width: 100%;
                                }
                            }
                            .availability-box{
                                 margin-top: 15px;
                                 width: 100%;
                                 /* min-height: 100px; */
                                 /* background-color: #f5f5f5; */
                                 display: flex;
                                 flex-wrap: wrap;
                                 justify-content: flex-start;
                                 align-items: center;
                                 .time-slot{
                                  /* background-color: var(--gh-primary); */
                                  display: flex;
                                  align-items: center;
                                  justify-content: center;
                                  margin: 8px 5px;
                                  width: 30%;
                                  height: 45px;
                                  border: 1px solid #ccc;
                                  padding: 5px;
                                  border-radius: 8px;
                                  cursor: pointer;
                                  /* color: #fff; */
                                  text-align: center;
                                  vertical-align: middle;
                                  font-size: 12px;
                                  font-weight: bold;
                                  position: relative;
                                  .is_booked{
                                    position: absolute;
                                    top: 0;
                                    right: 3px;
                                    font-size: 10px;
                                    color: var(--gh-price);
                                    font-family: '黑体';
                                 }
                                 .unbooked{
                                  position: absolute;
                                    top: 0;
                                    right: 3px;
                                    font-size: 10px;
                                    color: var(--gh-price);
                                    font-family: '黑体';
                                 }
                                 .is_selected{
                                    position: absolute;
                                    top: -5px;
                                    right: 0px;
                                    font-size: 20px;
                                    color: var(--gh-price);
                                    font-family: '黑体';
                                 }
                                 &.selected{
                                  background-color: lightblue;
                                 }
                                 &.booked{
                                  color: gray;
                                  opacity: 0.5;
                                  pointer-events: none;
                                  cursor: not-allowed;
                                 }
                                }
                             
                            }
                        }

                    }
                    .instructions{
                        height: 300px;
                        width: 100%;
                        margin: 40px 0 80px;
                        opacity: 0.8;
                        .ins_title{
                            text-align: center;
                            font-size: 17px;
                            font-weight: bold;
                            position: relative;
                            &::before,
                            &::after {
                              content: "";
                              position: absolute;
                              top: 50%;
                              width: 37%;
                              height: 1px;
                              background-color: var(--gh-line);
                            }
                         
                            &::before {
                              left: 0;
                            }
                         
                            &::after {
                              right: 0;
                            }
                        }
                        .ins_content{
                            width: 100%;
                            padding: 0 5px;
                            .f_title{
                                margin-top: 20px;
                               p{
                                margin-left: 5px;
                                font-size: 12px;
                                margin-top: 10px;
                                color: #808185;
                               }
                            }
                        }
                    }
                }
            }
        }


    }
    .booking_box{
        position: fixed;
        display: flex;
        padding: 0 25px;
        bottom: 0;
        left: 0;
        height: 60px;
        background-color: #fff;
        justify-content: center;
        align-items: center;
        text-align: center;
        width: 100%;
        .chat_o{
          width: 45px;
          height:45px;
          display: flex;
          flex-direction: column;
          justify-content: center;
          align-items: center;
          font-size: 12px;
          margin-right: 6px;
          .icon{
            font-size: 20px;
          }
        }
        .booking{
            /* width: 90%; */
            height: 45px;
            font-size: 18px;
            font-weight: bold;
            color: #fff;
            background: linear-gradient(to right, #05B0FC, #04DBAC);
        }
    }
    .content{
      .amount{
        padding:10px;
        text-align: center;
        font-size: 20px;
        font-weight: bold;
      }
      .btn{
        padding: 15px;
      }
      .van-cell{
        align-items: center;
        .gh-icon{
          margin-right: 10px;
          font-size: 18px;
        }
        .van-checkbox :deep(.van-checkbox__icon) {
              font-size: 16px;
    }
      }
    }
}

</style>
